﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BarCode.Common;
using System.IO;
using BarCode.Module;
using BarCode.AccessDao;
using System.Runtime.InteropServices;
using BarCode.Bean;

namespace BarCode.Forms
{
    public partial class Pack_BarCode : Form
    {

        private static readonly log4net.ILog LogUtil = log4net.LogManager.GetLogger(typeof(Pack_BarCode));

        public DataGridViewRow drPack { get; set; }

        private string range_MeterStart = "";                               // 存储本次测试的起始表号
        private string range_MeterEnd = "";                                 // 存储本次测试的终止表号
        private string range_PackStart = "";                                // 存储本次测试的起始封箱号
        private string range_PackEnd = "";                                  // 存储本次测试的终止封箱号

        private bool isPackTxtEnabled = false;                              // 判断当前封箱条码是否已到最后时文本框可用状态标志

        private string tmpPackCode = "";
        private string work_state = "";
        private string EMPTY_CODE = "";
        private int intA = 0;
        private string pack_barcodeIDstr = "";
        private int intAmountI = 0;
        private string[] strCode = new string[6];

        private int packCount = 0;

        private bool bPrintFlag = true;

        // 检查表号是否已经写入NFC
        private bool bCheckBHWrited = false;

        // 190505 表号长度
        private int BH_LEN = 0;
        private string BH_LEN_STR = "";

        [DllImport("user32.dll")]
        public static extern bool MessageBeep(uint uType);

        public Pack_BarCode()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 画面初期加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pack_BarCode_Load(object sender, EventArgs e)
        {
            try
            {
                LogUtil.Info("封箱页面准备启动---加载配置文件");
                // 打印是否设置
                string strPrintFlag = IniFileHelper.getStringValue("Pack", "Print_Flag");
                if (!String.IsNullOrEmpty(strPrintFlag) && "0".Equals(strPrintFlag))
                {
                    bPrintFlag = false;
                }

                // 检查表号是否已经写入NFC
                string strCheckBHWrited = IniFileHelper.getStringValue("Pack", "NFC_WRITED_CHECK");
                if (!String.IsNullOrEmpty(strCheckBHWrited) && "1".Equals(strCheckBHWrited))
                {
                    bCheckBHWrited = true;
                }

                ClearLblBarCode();

                if (GlobalVal.bolNetConnect)
                {
                    btnNet.Enabled = false;
                }
                else
                {
                    btnNet.Enabled = true;
                }

                packCount = Convert.ToInt32(drPack.Cells["packcount"].Value);

                // 距离微调
                cmbData.SelectedItem = "0";
                lblUser.Text = GlobalVal.CurrentUser.User;

                LogUtil.Info("封箱页面准备启动---加载客户数据");
                // 客户名称
                TmpOutRoomMdbDao tmpOutRoomMdbDao = new TmpOutRoomMdbDao();
                cobcustomer.DataSource = tmpOutRoomMdbDao.selectCustomerNames();
                cobcustomer.DisplayMember = "customer_name";
                cobcustomer.ValueMember = "customer_name";
                tmpOutRoomMdbDao.Release();
                //txtCustomer.Text = Convert.ToString(drPack.Cells["customer_name"].Value);
                cobcustomer.SelectedValue = Convert.ToString(drPack.Cells["customer_name"].Value);

                work_state = "工作";
                lblState.Text = work_state;
                lblState.ForeColor = Color.Blue;
                lblInfo.Text = "当前为正常工作状态！";
                range_PackStart = Convert.ToString(drPack.Cells["packID_start"].Value);
                range_PackEnd = Convert.ToString(drPack.Cells["packID_end"].Value);
                txtpack_Start.Text = range_PackStart;
                txtpack_End.Text = range_PackEnd;

                range_MeterStart = Convert.ToString(drPack.Cells["meters_IDstart"].Value);
                range_MeterEnd = Convert.ToString(drPack.Cells["meters_IDend"].Value);

                // 190505 表号长度
                BH_LEN = range_MeterStart.Length;
                BH_LEN_STR = "(" + BH_LEN + "位)";

                // 生成备份数据库
                LogUtil.Info("封箱页面准备启动---生成备份数据库");
                string bakBarcodeMdb = GlobalVal.BK_PATH + "barcode_" + DateTime.Today.ToString("yyyyMMdd") + ".mdb";
                if (!File.Exists(bakBarcodeMdb))
                {
                    if (!Directory.Exists(GlobalVal.BK_PATH))
                    {
                        Directory.CreateDirectory(GlobalVal.BK_PATH);
                    }
                    // 复制文件
                    FileHelper.CopyFile(AppDomain.CurrentDomain.BaseDirectory + "barcode.mdb", bakBarcodeMdb);
                    FileHelper.CopyFile(AppDomain.CurrentDomain.BaseDirectory + "Empty_barcode.mdb", AppDomain.CurrentDomain.BaseDirectory + "barcode.mdb");
                }

                LogUtil.Info("封箱页面准备启动---获取封箱条码起始编号");
                DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                if (db01.EnableConnect())
                {
                    // 如果网络通，则从网络数据库中查询获得当前封箱条码起始编号
                    pack_barcodeIDstr = db01.getStartPackBarcodeId(range_PackStart, range_PackEnd);
                }
                else
                {
                    // 如果网络不通，则从本地数据库tmp_packID.mdb中查询获得当前封箱条码起始编号
                    TmpPackMdbDao tmpPackMdbDao = new TmpPackMdbDao();
                    pack_barcodeIDstr = tmpPackMdbDao.getStartPackBarcodeId(range_PackStart, range_PackEnd);
                    tmpPackMdbDao.Release();
                }

                if (pack_barcodeIDstr.CompareTo(range_PackEnd) > 0)
                {
                    lblInfo.Text = "该批表已封箱完毕！请审核！";
                    lblInfo.ForeColor = Color.Red;
                    txtBarCode.Enabled = false;
                    txtPackCode.Enabled = false;
                    isPackTxtEnabled = true;
                    return;
                }

                txtBarCode.Text = "";
                txtPackCode.Text = pack_barcodeIDstr;

                // 获取当前用户当天的工作量
                LogUtil.Info("封箱页面准备启动---当前用户当天的工作量");
                if (GlobalVal.bolNetConnect)
                {
                    int workAmount = db01.getPackWorkAmount(GlobalVal.CurrentUser.User);
                    lblAmount.Text = (workAmount + GlobalVal.offSetInfo.packoffset).ToString();
                }
                else
                {
                    BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                    int workAmount = barcodeMdbDao.getPackWorkAmount(GlobalVal.CurrentUser.User);
                    barcodeMdbDao.Release();

                    BarCodeMdbDao bkBarcodeMadbDao = new BarCodeMdbDao(bakBarcodeMdb);
                    workAmount += bkBarcodeMadbDao.getPackWorkAmount(GlobalVal.CurrentUser.User);
                    bkBarcodeMadbDao.Release();

                    if (DateTime.Now.ToString("HHmmss").CompareTo(GlobalVal.WORK_START_TIME) < 0)
                    {
                        string yesterdayBarcodeMdb = GlobalVal.BK_PATH + "barcode_" + DateTime.Today.AddDays(-1).ToString("yyyyMMdd") + ".mdb";
                        BarCodeMdbDao yesterdayBarcodeMadbDao = new BarCodeMdbDao(yesterdayBarcodeMdb);
                        workAmount += yesterdayBarcodeMadbDao.getPackWorkAmount(GlobalVal.CurrentUser.User);
                        yesterdayBarcodeMadbDao.Release();
                    }

                    lblAmount.Text = (workAmount + GlobalVal.offSetInfo.packoffset).ToString();
                }
                LogUtil.Info("封箱页面准备启动---页面启动完成");
                txtBarCode.Focus();

            }
            catch (Exception ex)
            {
                LogUtil.Error(ex);
            }
        }

        /// <summary>
        /// 更改客户名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cobcustomer_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine(cobcustomer.SelectedValue+"111");
                //if (cobcustomer.SelectedValue.ToString() == "合肥燃气集团")
                if ("合肥燃气集团".Equals(cobcustomer.SelectedValue.ToString()))
                {
                    EMPTY_CODE = "400000000000";
                    intA = 5;
                    lblHint5.Visible = true;
                    lblHint6.Visible = true;
                    lblbarcode5.Visible = true;
                    lblbarcode6.Visible = true;
                }
                //else if (cobcustomer.SelectedValue.ToString() == "沈阳燃气公司")
                else if ("沈阳燃气公司".Equals(cobcustomer.SelectedValue.ToString()))
                {
                    EMPTY_CODE = "20000000000";
                    intA = 3;
                    lblHint5.Visible = false;
                    lblHint6.Visible = false;
                    lblbarcode5.Visible = false;
                    lblbarcode6.Visible = false;
                }
                else
                {
                    EMPTY_CODE = "200000000000";
                    // 2019-03-14 逆光微信 更改说明 增加packCount的判断
                    if (packCount == 6)
                    {
                        intA = 5;
                        lblHint5.Visible = true;
                        lblHint6.Visible = true;
                        lblbarcode5.Visible = true;
                        lblbarcode6.Visible = true;
                    }
                    else
                    {
                        intA = 3;
                        lblHint5.Visible = false;
                        lblHint6.Visible = false;
                        lblbarcode5.Visible = false;
                        lblbarcode6.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex);
                intA = 3;
                lblHint5.Visible = false;
                lblHint6.Visible = false;
                lblbarcode5.Visible = false;
                lblbarcode6.Visible = false;
            }
        }

        private void btnNet_Click(object sender, EventArgs e)
        {
            DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
            if (db01.EnableConnect() && Consts.CONNECT_SUCCESS.Equals(db01.getConnetText()))
            {
                GlobalVal.bolNetConnect = true;
                btnNet.Enabled = false;
            }
            else
            {
                GlobalVal.bolNetConnect = false;
                btnNet.Enabled = true;
            }
        }

        private void Pack_BarCode_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (GlobalVal.bolNetConnect)
            {
                GlobalVal.bolUploadSubMain = false;
                modeFunction.Upload_PackData(intA);
            }
            //Application.Exit();
        }

        /// <summary>
        /// 扫描条码
        /// </summary>
        private void txtBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar != (char)13)
                {
                    return;
                }

                bool bolIsContinue = true;
                //if (cobcustomer.SelectedValue.ToString() == "合肥燃气集团")
                //{
                //    intA = 5;
                //}
                //else 
                //{
                //    intA = 3;
                //}
                lblInfo.Text = "";

                if (cobcustomer.SelectedValue.ToString().Contains("南海燃气") || cobcustomer.SelectedValue.ToString().Contains("瀚蓝"))
                {
                    string fullString = txtBarCode.Text;
                    LogUtil.Info("南海燃气/瀚蓝扫描原始字符串：" + fullString);
                    string[] strArray = fullString.Split(';');
                    txtBarCode.Text = strArray[0];
                }

                // 条码位数检查
                string BarCode = txtBarCode.Text;
                if (BarCode.Length < 10 || BarCode.Length > 18)
                {
                    lblInfo.Text = "条码信息位数不正确！";
                    clearTxtBarCode();
                    return;
                }

                // 190505 表号位数
                //if (BarCode.Length == 11 && cobcustomer.SelectedValue.ToString() != "沈阳燃气公司")
                //{
                //    lblInfo.Text = "非沈阳表号不允许11位！";
                //    clearTxtBarCode();
                //    return;
                //}




                if (BarCode.StartsWith(Consts.JXCODE1) || BarCode.StartsWith(Consts.JXCODE2)  || BarCode.StartsWith(Consts.JKCODE))
                {
                    lblInfo.Text = "无效条码信息不能扫描！";
                    clearTxtBarCode();
                    return;
                }

                switch (BarCode)
                {
                    case Consts.STATE_CODE1:
                        // 当前为工作状态
                        work_state = "工作";
                        clearTxtBarCode();
                        lblState.Text = work_state;
                        lblInfo.Text = "当前为正常工作状态！";
                        lblState.ForeColor = Color.Blue;

                        ClearLblBarCode();
                        intAmountI = 0;
                        return;
                    case Consts.STATE_CODE2:
                        // 当前为补打状态
                        work_state = "补打";
                        clearTxtBarCode();
                        lblState.Text = work_state;
                        lblInfo.Text = "当前为补打条码状态，请扫描您需要补打的条码！";
                        lblState.ForeColor = Color.Red;

                        ClearLblBarCode();
                        intAmountI = 0;
                        return;
                    case Consts.STATE_CODE3:
                        // 当前为补码状态
                        work_state = "换码";
                        clearTxtBarCode();
                        lblState.Text = work_state;
                        lblInfo.Text = "当前为更换条码状态，请扫描您需要更换的箱号和表号！";
                        lblState.ForeColor = Color.Red;

                        ClearLblBarCode();
                        intAmountI = 0;
                        return;
                    case Consts.PRINT_CODE:

                        for (int i = 0; i <= intA; i++)
                        {
                            if (String.IsNullOrEmpty(strCode[i]))
                            {
                                lblInfo.Text = "条码信息为空！";
                                clearTxtBarCode();
                                return;
                            }
                        }

                        if (String.IsNullOrEmpty(txtPackCode.Text))
                        {
                            lblInfo.Text = "打印前请先输入封箱条码信息！";
                            clearTxtBarCode();
                            txtPackCode.Focus();
                            return;
                        }
                        if (txtPackCode.Text.CompareTo(range_PackStart) < 0 || txtPackCode.Text.CompareTo(range_PackEnd) > 0)
                        {
                            lblInfo.Text = "封箱条码超出范围！";
                            clearTxtBarCode();
                            txtPackCode.Focus();
                            return;
                        }
                        //if (cobcustomer.SelectedValue == null || cobcustomer.SelectedValue.ToString() == "")
                        if (cobcustomer.SelectedValue.ToString() == "")  
                        {
                            lblInfo.Text = "打印前请先输入客户信息！";
                            clearTxtBarCode();
                            cobcustomer.Focus();
                            return;
                        }
                        // 下面是将表号按照从小到大顺序排列的语句
                        string tmpCode = "";
                        for (int i = 0; i <= intA; i++)
                        {
                            for (int j = i + 1; j <= intA; j++)
                            {
                                if (strCode[i].CompareTo(strCode[j]) > 0)
                                {
                                    tmpCode = strCode[i];
                                    strCode[i] = strCode[j];
                                    strCode[j] = tmpCode;
                                }
                            }
                        }

                        // 保存封箱条码信息
                        LogUtil.Debug("本地保存封箱条码信息...");
                        BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                        SavePackInfo savePackInfo = new SavePackInfo();
                        savePackInfo.EMPTY_CODE = EMPTY_CODE;
                        savePackInfo.CustomerName = cobcustomer.SelectedValue.ToString();
                        savePackInfo.intAmount = intA;
                        savePackInfo.pack_barcodeID = txtPackCode.Text;
                        savePackInfo.strCode = strCode;
                        string errMsg = barcodeMdbDao.SavePackData(savePackInfo);
                        barcodeMdbDao.Release();
                        if (!String.IsNullOrEmpty(errMsg))
                        {
                            lblInfo.Text = errMsg;
                            clearTxtBarCode();
                            return;
                        }


                        // 保存当前封箱条码值
                        LogUtil.Debug("本地保存当前封箱条码值...");
                        TmpPackMdbDao tmpPackMdbDao = new TmpPackMdbDao();
                        bool mdbRet = tmpPackMdbDao.savePackInfo(range_PackStart, range_PackEnd, txtPackCode.Text);
                        tmpPackMdbDao.Release();
                        if (!mdbRet)
                        {
                            LogUtil.Error("本地保存当前封箱条码值失败！！！");
                            return;
                        }

                        DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                        if (db01.EnableConnect())
                        {
                            GlobalVal.bolNetConnect = true;
                            Application.DoEvents();
                            GlobalVal.bolUploadSubMain = false;
                            LogUtil.Debug("即时上传封箱条码信息...");
                            bolIsContinue = modeFunction.Upload_PackData(intA);
                            if (!bolIsContinue)
                            {
                                lblInfo.Text = "封箱条码重复扫描！";
                                clearTxtBarCode();
                            }
                        }
                        else
                        {
                            GlobalVal.bolNetConnect = false;
                        }

                        LogUtil.Debug("重新加载工作量...");
                        // 获取当前用户当天的工作量
                        if (GlobalVal.bolNetConnect)
                        {
                            // 获取偏移量信息
                            GlobalVal.offSetInfo.packoffset = db01.getOffSetValue(Consts.WORK_POSITION_PACK);
                            int workAmount = db01.getPackWorkAmount(GlobalVal.CurrentUser.User);
                            lblAmount.Text = (workAmount + GlobalVal.offSetInfo.packoffset).ToString();
                        }
                        else
                        {
                            BarCodeMdbDao wabarcodeMdbDao = new BarCodeMdbDao();
                            int workAmount = wabarcodeMdbDao.getPackWorkAmount(GlobalVal.CurrentUser.User);
                            wabarcodeMdbDao.Release();
                            string bakBarcodeMdb = GlobalVal.BK_PATH + "barcode_" + DateTime.Today.ToString("yyyyMMdd") + ".mdb";
                            BarCodeMdbDao bkBarcodeMadbDao = new BarCodeMdbDao(bakBarcodeMdb);
                            workAmount += bkBarcodeMadbDao.getPackWorkAmount(GlobalVal.CurrentUser.User);
                            bkBarcodeMadbDao.Release();

                            if (DateTime.Now.ToString("HHmmss").CompareTo(GlobalVal.WORK_START_TIME) < 0)
                            {
                                string yesterdayBarcodeMdb = GlobalVal.BK_PATH + "barcode_" + DateTime.Today.AddDays(-1).ToString("yyyyMMdd") + ".mdb";
                                BarCodeMdbDao yesterdayBarcodeMadbDao = new BarCodeMdbDao(yesterdayBarcodeMdb);
                                workAmount += yesterdayBarcodeMadbDao.getPackWorkAmount(GlobalVal.CurrentUser.User);
                                yesterdayBarcodeMadbDao.Release();
                            }

                            lblAmount.Text = (workAmount + GlobalVal.offSetInfo.packoffset).ToString();
                        }

                        if (!bolIsContinue)
                        {
                            ClearLblBarCode();
                            intAmountI = 0;
                            return;
                        }


                        for (int i = 0; i <= intA; i++)
                        {
                            if ("400000000000".Equals(strCode[i]) || "200000000000".Equals(strCode[i]))
                            {
                                strCode[i] = "000000000000";
                            }
                            else if ("20000000000".Equals(strCode[i]))
                            {
                                strCode[i] = "00000000000";
                            }
                        }

                        Application.DoEvents();
                        if (bPrintFlag)
                        {
                            LogUtil.Debug("开始打印...");
                            // 打印
                            PrintBarCodeInfo printInfo = new PrintBarCodeInfo();
                            printInfo.intCount = intA + 1;
                            printInfo.intDist = Convert.ToInt32(cmbData.SelectedItem.ToString());
                            printInfo.intModel = getPrintModel(cobcustomer.SelectedValue.ToString()); // 也是根据公司名称来
                            printInfo.mDirections = Convert.ToString(drPack.Cells["meters_directions"].Value);
                            printInfo.mType = Convert.ToString(drPack.Cells["meters_code"].Value);
                            printInfo.packCode = txtPackCode.Text;
                            printInfo.packCount = Convert.ToInt32(drPack.Cells["packcount"].Value);
                            printInfo.productDate = Convert.ToDateTime(drPack.Cells["opdt"].Value);
                            printInfo.strCode = strCode;
                            printInfo.strCustomer = cobcustomer.SelectedValue.ToString();
                            printInfo.strPrtName = GlobalVal.ipAddressInfo.PRINTER_NAME;
                            printInfo.strPrtNum = 1;
                            printInfo.driveMode = chkDriveMode.Checked; // 2020.07.07 Add 传动方式
                            BarCodePrint.PrintBarCode(printInfo);

                            LogUtil.Debug("打印完毕...");
                            lblInfo.Text = "条码信息打印完毕！";
                        }
                        else
                        {
                            lblInfo.Text = "条码信息保存完毕！";
                        }

                        ClearLblBarCode();
                        intAmountI = 0;

                        Application.DoEvents();

                        txtPackCode.Text = (Convert.ToInt64(txtPackCode.Text) + 1).ToString();
                        clearTxtBarCode();
                        return;
                    default:
                        break;
                }


                if ("工作".Equals(work_state))
                {
                    lblInfo.Text = "";
                    for (int i = 0; i <= intA; i++)
                    {
                        if (txtBarCode.Text.Equals(strCode[i]) && !txtBarCode.Text.Equals(EMPTY_CODE))
                        {
                            clearTxtBarCode();
                            lblInfo.Text = "条码信息重复！";
                            return;
                        }
                    }

                    // 190505 表号长度
                    if (txtBarCode.Text.Length != BH_LEN && !EMPTY_CODE.Equals(txtBarCode.Text))
                    {
                        lblInfo.Text = "条码位数不正确" + BH_LEN_STR;
                        clearTxtBarCode();
                        return;
                    }


                    // 如果当前表号在表号范围之内或为空表号，则OK
                    if ((txtBarCode.Text.CompareTo(range_MeterStart) >= 0 && txtBarCode.Text.CompareTo(range_MeterEnd) <= 0)
                        || EMPTY_CODE.Equals(txtBarCode.Text))
                    {
                    }
                    else
                    {
                        lblInfo.Text = "条码超出范围！";
                        clearTxtBarCode();
                        return;
                    }

                    // 2019-03-13 增加表号判断处理
                    if (!EMPTY_CODE.Equals(txtBarCode.Text))
                    {
                        DB02Dao db02 = new DB02Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                        string errMsg = db02.checkBH(txtBarCode.Text);
                        if (!String.IsNullOrEmpty(errMsg))
                        {
                            lblInfo.ForeColor = Color.Red;
                            lblInfo.Text = errMsg;
                            clearTxtBarCode();
                            return;
                        }
                        else
                        {
                            lblInfo.ForeColor = Color.Blue;
                        }
                    }

                    // 2020-05-31 增加表号检查是否写入NFC
                    if (!EMPTY_CODE.Equals(txtBarCode.Text) && bCheckBHWrited)
                    {
                        DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                        string errMsg = db01.CheckBHWritedByNFC(txtBarCode.Text);
                        if (!String.IsNullOrEmpty(errMsg))
                        {
                            lblInfo.ForeColor = Color.Red;
                            lblInfo.Text = errMsg;
                            clearTxtBarCode();
                            return;
                        }
                        else
                        {
                            lblInfo.ForeColor = Color.Blue;
                        }
                    }

                    switch (intAmountI % (intA + 1))
                    {
                        case 0:
                            strCode[0] = txtBarCode.Text;
                            lblbarcode1.Text = txtBarCode.Text;
                            break;
                        case 1:
                            strCode[1] = txtBarCode.Text;
                            lblbarcode2.Text = txtBarCode.Text;
                            break;
                        case 2:
                            strCode[2] = txtBarCode.Text;
                            lblbarcode3.Text = txtBarCode.Text;
                            break;
                        case 3:
                            strCode[3] = txtBarCode.Text;
                            lblbarcode4.Text = txtBarCode.Text;
                            break;
                        case 4:
                            strCode[4] = txtBarCode.Text;
                            lblbarcode5.Text = txtBarCode.Text;
                            break;
                        case 5:
                            strCode[5] = txtBarCode.Text;
                            lblbarcode6.Text = txtBarCode.Text;
                            break;
                        default:
                            break;
                    }
                    intAmountI++;
                    clearTxtBarCode();

                }
                else if ("换码".Equals(work_state))
                {
                    if (txtBarCode.Text.StartsWith("6"))
                    {
                        tmpPackCode = txtBarCode.Text;
                        clearTxtBarCode();
                        return;
                    }

                    lblInfo.Text = "";
                    for (int i = 0; i <= intA; i++)
                    {
                        if (txtBarCode.Text.Equals(strCode[i]) && !txtBarCode.Text.Equals(EMPTY_CODE))
                        {
                            clearTxtBarCode();
                            lblInfo.Text = "条码信息重复！";
                            return;
                        }
                    }
                    // 如果当前表号在表号范围之内或为空表号，则OK
                    if ((txtBarCode.Text.CompareTo(range_MeterStart) >= 0 && txtBarCode.Text.CompareTo(range_MeterEnd) <= 0)
                        || EMPTY_CODE.Equals(txtBarCode.Text))
                    {
                    }
                    else
                    {
                        lblInfo.Text = "条码超出范围！";
                        clearTxtBarCode();
                        return;
                    }

                    switch (intAmountI % (intA + 1))
                    {
                        case 0:
                            strCode[0] = txtBarCode.Text;
                            lblbarcode1.Text = txtBarCode.Text;
                            break;
                        case 1:
                            strCode[1] = txtBarCode.Text;
                            lblbarcode2.Text = txtBarCode.Text;
                            break;
                        case 2:
                            strCode[2] = txtBarCode.Text;
                            lblbarcode3.Text = txtBarCode.Text;
                            break;
                        case 3:
                            strCode[3] = txtBarCode.Text;
                            lblbarcode4.Text = txtBarCode.Text;
                            break;
                        case 4:
                            strCode[4] = txtBarCode.Text;
                            lblbarcode5.Text = txtBarCode.Text;
                            break;
                        case 5:
                            strCode[5] = txtBarCode.Text;
                            lblbarcode6.Text = txtBarCode.Text;
                            break;
                        default:
                            break;
                    }
                    intAmountI++;
                    clearTxtBarCode();
                    if (intAmountI < (intA + 1))
                    {
                        return;
                    }

                    for (int i = 0; i <= intA; i++)
                    {
                        if (String.IsNullOrEmpty(strCode[i]))
                        {
                            clearTxtBarCode();
                            lblInfo.Text = "条码信息为空！";
                            return;
                        }
                    }

                    // 下面是将表号按照从小到大顺序排列的语句
                    string tmpCode = "";
                    for (int i = 0; i <= intA; i++)
                    {
                        for (int j = i + 1; j <= intA; j++)
                        {
                            if (strCode[i].CompareTo(strCode[j]) > 0)
                            {
                                tmpCode = strCode[i];
                                strCode[i] = strCode[j];
                                strCode[j] = tmpCode;
                            }
                        }
                    }

                    if (GlobalVal.bolNetConnect)
                    {
                        if (String.IsNullOrEmpty(tmpPackCode))
                        {
                            clearTxtBarCode();
                            lblInfo.Text = "未扫描要更换的封箱条码！";
                            return;
                        }
                        else
                        {
                            DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                            db01.ChangePackCode(strCode, tmpPackCode, intA);
                        }
                        ClearLblBarCode();
                        intAmountI = 0;
                    }
                    else
                    {
                        MessageUtil.Error("由于网络错误,换号失败!请咨询管理员!");
                        return;
                    }

                }
                else if ("补打".Equals(work_state))
                {
                    string str_state = "";
                    string[] strRepair = new string[5];
                    str_state = txtBarCode.Text;
                    if (str_state.StartsWith("04"))     // 合肥公司通过查询表号获得补打信息
                    {
                        // 打印
                        PrintBarCodeInfo printInfo = new PrintBarCodeInfo();
                        printInfo.intCount = 6;
                        printInfo.intDist = Convert.ToInt32(cmbData.SelectedItem.ToString());
                        printInfo.intModel = getPrintModel(cobcustomer.SelectedValue.ToString()); // 也是根据公司名称来
                        printInfo.mDirections = Convert.ToString(drPack.Cells["meters_directions"].Value);
                        printInfo.mType = Convert.ToString(drPack.Cells["meters_code"].Value);
                        printInfo.packCount = Convert.ToInt32(drPack.Cells["packcount"].Value);
                        printInfo.productDate = Convert.ToDateTime(drPack.Cells["opdt"].Value);
                        printInfo.strCustomer = cobcustomer.SelectedValue.ToString();
                        printInfo.strPrtName = GlobalVal.ipAddressInfo.PRINTER_NAME;
                        printInfo.strPrtNum = 1;
                        printInfo.driveMode = chkDriveMode.Checked; // 2020.07.07 Add 传动方式
                        if (GlobalVal.bolNetConnect)
                        {
                            DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                            bool existRet = db01.getPrintInfoByBH(str_state, 5, printInfo);
                            if (existRet)
                            {
                                BarCodePrint.PrintBarCode(printInfo);
                            }
                            else
                            {
                                lblInfo.Text = "未找到要补打的信息！";
                            }
                            clearTxtBarCode();
                        }
                        else
                        {
                            BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                            bool existRet = barcodeMdbDao.getPrintInfoByBH(str_state, 5, printInfo);
                            if (existRet)
                            {
                                BarCodePrint.PrintBarCode(printInfo);
                            }
                            else
                            {
                                lblInfo.Text = "未找到要补打的信息！";
                            }
                            barcodeMdbDao.Release();
                            clearTxtBarCode();

                        }
                    }
                    else if (str_state.StartsWith("06"))     // 通过查询封箱条码获得补打信息 
                    {
                        // 打印
                        PrintBarCodeInfo printInfo = new PrintBarCodeInfo();
                        printInfo.intCount = intA + 1;
                        printInfo.intDist = Convert.ToInt32(cmbData.SelectedItem.ToString());
                        printInfo.intModel = getPrintModel(cobcustomer.SelectedValue.ToString()); // 也是根据公司名称来
                        printInfo.mDirections = drPack.Cells["meters_directions"].Value.ToString();
                        printInfo.mType = drPack.Cells["meters_code"].Value.ToString();
                        printInfo.packCount = Convert.ToInt32(drPack.Cells["packcount"].Value.ToString());
                        printInfo.productDate = Convert.ToDateTime(drPack.Cells["opdt"].Value);
                        printInfo.strPrtName = GlobalVal.ipAddressInfo.PRINTER_NAME;
                        printInfo.strPrtNum = 1;
                        printInfo.driveMode = chkDriveMode.Checked; // 2020.07.07 Add 传动方式
                        if (GlobalVal.bolNetConnect)
                        {
                            DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                            bool existRet = db01.getPrintInfoByXH(str_state, printInfo);
                            if (existRet)
                            {
                                BarCodePrint.PrintBarCode(printInfo);
                            }
                            else
                            {
                                lblInfo.Text = "未找到要补打的信息！";
                            }
                            clearTxtBarCode();
                        }
                        else
                        {
                            BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                            bool existRet = barcodeMdbDao.getPrintInfoByXH(str_state, printInfo);
                            if (existRet)
                            {
                                BarCodePrint.PrintBarCode(printInfo);
                            }
                            else
                            {
                                lblInfo.Text = "未找到要补打的信息！";
                            }
                            barcodeMdbDao.Release();
                            clearTxtBarCode();

                        }
                    }
                    else        //  '不是合肥公司通过查询表号获得补打信息
                    {
                        // 打印
                        PrintBarCodeInfo printInfo = new PrintBarCodeInfo();
                        printInfo.intCount = packCount;
                        printInfo.intDist = Convert.ToInt32(cmbData.SelectedItem.ToString());
                        printInfo.intModel = getPrintModel(cobcustomer.SelectedValue.ToString()); // 也是根据公司名称来
                        printInfo.mDirections = Convert.ToString(drPack.Cells["meters_directions"].Value);
                        printInfo.mType = Convert.ToString(drPack.Cells["meters_code"].Value);
                        printInfo.packCount = Convert.ToInt32(drPack.Cells["packcount"].Value);
                        printInfo.productDate = Convert.ToDateTime(drPack.Cells["opdt"].Value);
                        printInfo.strPrtName = GlobalVal.ipAddressInfo.PRINTER_NAME;
                        printInfo.strPrtNum = 1;
                        printInfo.driveMode = chkDriveMode.Checked; // 2020.07.07 Add 传动方式
                        if (GlobalVal.bolNetConnect)
                        {
                            DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                            bool existRet = db01.getPrintInfoByBH(str_state, packCount - 1, printInfo);
                            if (existRet)
                            {
                                BarCodePrint.PrintBarCode(printInfo);
                            }
                            else
                            {
                                lblInfo.Text = "未找到要补打的信息！";
                            }
                            clearTxtBarCode();
                        }
                        else
                        {
                            BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                            bool existRet = barcodeMdbDao.getPrintInfoByBH(str_state, 3, printInfo);
                            if (existRet)
                            {
                                BarCodePrint.PrintBarCode(printInfo);
                            }
                            else
                            {
                                lblInfo.Text = "未找到要补打的信息！";
                            }
                            barcodeMdbDao.Release();
                            clearTxtBarCode();

                        }
                    }

                }



            }
            catch (Exception ex)
            {
                LogUtil.Error(ex);
            }
        }

        /// <summary>
        /// 打印测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTestPrint_Click(object sender, EventArgs e)
        {
            PrintBarCodeInfo testPrintInfo = new PrintBarCodeInfo();
            string[] strCodeInfo = new string[6];
            strCodeInfo[0] = "012345678901";
            strCodeInfo[1] = "123456789012";
            strCodeInfo[2] = "012345678901";
            strCodeInfo[3] = "012345678901";
            strCodeInfo[4] = "012345678901";
            strCodeInfo[5] = "012345678901";
            testPrintInfo.strCode = strCodeInfo;
            testPrintInfo.intCount = 4;
            testPrintInfo.intDist = 0;
            testPrintInfo.intModel = 1;
            testPrintInfo.packCode = "612345678901";
            testPrintInfo.strCustomer = "沈阳燃气公司";
            testPrintInfo.strPrtNum = 1;
            BarCodePrint.PrintBarCode(testPrintInfo);

        }

        /// <summary>
        /// 缺号审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFind_Click(object sender, EventArgs e)
        {
            LogUtil.Debug("缺号审核开始");
            DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
            if (db01.EnableConnect())
            {
                GlobalVal.bolNetConnect = true;
                btnNet.Enabled = false;

                if (String.IsNullOrEmpty(range_MeterStart) || String.IsNullOrEmpty(range_MeterEnd))
                {
                    MessageUtil.Warn("表号范围不正确，无法审核！");
                    return;
                }

                int loopStart = Convert.ToInt32(range_MeterStart.Substring(range_MeterStart.Length - 5));
                int loopEnd = Convert.ToInt32(range_MeterEnd.Substring(range_MeterEnd.Length - 5));

                string tmpI = "";
                string tmpBH = "";
                int leaveCnt = 0;
                List<PackLeaveInfo> lstLeaveInfo = new List<PackLeaveInfo>();
                List<PackLeaveXHInfo> lstLeaveXHInfo = new List<PackLeaveXHInfo>();


                //for (int loopIdx = loopStart; loopIdx <= loopEnd; loopIdx++)
                //{
                //    tmpI = loopIdx.ToString().PadLeft(5, '0');
                //    lblState.Text = "已查询表号数量：" + Convert.ToString(loopIdx - loopStart + 1);

                //    if (range_MeterStart.Length == 11)
                //    {
                //        tmpBH = range_MeterStart.Substring(0, 6) + tmpI;
                //    }
                //    else if (range_MeterStart.Length == 12)
                //    {
                //        tmpBH = range_MeterStart.Substring(0, 7) + tmpI;
                //    }
                //    else if (range_MeterStart.Length == 17)
                //    {
                //        tmpBH = range_MeterStart.Substring(0, 12) + tmpI;
                //    }

                //    Application.DoEvents();
                //    if (!db01.existBH(tmpBH, intA))
                //    {
                //        leaveCnt++;
                //        PackLeaveInfo tmpLeaveInfo = new PackLeaveInfo();
                //        tmpLeaveInfo.No = leaveCnt;
                //        tmpLeaveInfo.leaveBH = tmpBH;
                //        lstLeaveInfo.Add(tmpLeaveInfo);
                //    }
                //}


                Application.DoEvents();
                List<String> lstAllXH = new List<String>();
                List<String> lstAllBH = db01.getAllBH(range_MeterStart, range_MeterEnd, range_PackStart, range_PackEnd, ref lstAllXH);
                for (int loopIdx = loopStart; loopIdx <= loopEnd; loopIdx++)
                {
                    tmpI = loopIdx.ToString().PadLeft(5, '0');
                    lblState.Text = "已查询表号数量：" + Convert.ToString(loopIdx - loopStart + 1);

                    //if (range_MeterStart.Length == 11)
                    //{
                    //    tmpBH = range_MeterStart.Substring(0, 6) + tmpI;
                    //}
                    //else if (range_MeterStart.Length == 12)
                    //{
                    //    tmpBH = range_MeterStart.Substring(0, 7) + tmpI;
                    //}
                    //else if (range_MeterStart.Length == 16)
                    //{
                    //    tmpBH = range_MeterStart.Substring(0, 11) + tmpI;
                    //}
                    //else if (range_MeterStart.Length == 17)
                    //{
                    //    tmpBH = range_MeterStart.Substring(0, 12) + tmpI;
                    //}
                    tmpBH = range_MeterStart.Substring(0, range_MeterStart.Length - 5) + tmpI;

                    if (!lstAllBH.Contains(tmpBH))
                    {
                        leaveCnt++;
                        PackLeaveInfo tmpLeaveInfo = new PackLeaveInfo();
                        tmpLeaveInfo.No = leaveCnt;
                        tmpLeaveInfo.leaveBH = tmpBH;
                        lstLeaveInfo.Add(tmpLeaveInfo);
                    }
                }

                int loopXStart = Convert.ToInt32(range_PackStart.Substring(range_PackStart.Length - 5));
                int loopXEnd = Convert.ToInt32(range_PackEnd.Substring(range_PackEnd.Length - 5));
                string tmpXH = "";
                for (int loopIdx = loopXStart; loopIdx <= loopXEnd; loopIdx++)
                {
                    tmpI = loopIdx.ToString().PadLeft(5, '0');
                    tmpXH = range_PackStart.Substring(0, range_PackStart.Length - 5) + tmpI;
                    if (!lstAllXH.Contains(tmpXH))
                    {
                        leaveCnt++;
                        PackLeaveXHInfo tmpLeaveInfo = new PackLeaveXHInfo();
                        tmpLeaveInfo.No = leaveCnt;
                        tmpLeaveInfo.leaveXH = tmpXH;
                        lstLeaveXHInfo.Add(tmpLeaveInfo);
                    }
                }

                LogUtil.Debug("缺号审核检索处理结束。");
                if (leaveCnt == 0)
                {
                    // 全部封箱
                    int ret = db01.completePack(drPack);
                    if (ret == Consts.RET_FAIL)
                    {
                        LogUtil.Error("数据库更新失败！");
                        MessageUtil.Error("数据库更新失败，请咨询管理员！");
                        return;
                    }
                    lblInfo.Text = "该批表已全部封箱！请选择下批封箱任务！";
                    lblInfo.ForeColor = Color.Red;
                    lblState.Text = work_state;
                    btnFind.Enabled = false;
                    txtBarCode.Enabled = false;
                    txtPackCode.Enabled = false;
                }
                else
                {
                    frmPackLeave objLeaveForm = new frmPackLeave();
                    objLeaveForm.lstLeaveInfo = lstLeaveInfo;
                    objLeaveForm.lstLeaveXHInfo = lstLeaveXHInfo;
                    objLeaveForm.Text = "范围缺失表号&箱号浏览窗体";
                    objLeaveForm.ShowDialog();
                    btnFind.Enabled = true;
                    txtBarCode.Enabled = true;
                    txtPackCode.Enabled = true;
                    txtBarCode.Focus();
                }
            }
            else
            {
                GlobalVal.bolNetConnect = false;
                btnNet.Enabled = true;
                MessageUtil.Warn("网络错误，请咨询管理员！");
            }

        }

        /// <summary>
        /// 重号审核
        /// </summary>
        private void btnRepeat_Click(object sender, EventArgs e)
        {
            DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
            if (db01.EnableConnect())
            {
                GlobalVal.bolNetConnect = true;
                btnNet.Enabled = false;

                if (String.IsNullOrEmpty(range_MeterStart) || String.IsNullOrEmpty(range_MeterEnd))
                {
                    MessageUtil.Warn("表号范围不正确，无法审核！");
                    return;
                }

                int loopStart = Convert.ToInt32(range_MeterStart.Substring(range_MeterStart.Length - 5));
                int loopEnd = Convert.ToInt32(range_MeterEnd.Substring(range_MeterEnd.Length - 5));

                string tmpI = "";
                string tmpBH = "";
                int repeatCnt = 0;
                List<PackRepeatInfo> lstRepeatInfo = new List<PackRepeatInfo>();


                //for (int loopIdx = loopStart; loopIdx <= loopEnd; loopIdx++)
                //{
                //    tmpI = loopIdx.ToString().PadLeft(5, '0');
                //    lblState.Text = "已查询表号数量：" + Convert.ToString(loopIdx - loopStart + 1);

                //    if (range_MeterStart.Length == 11)
                //    {
                //        tmpBH = range_MeterStart.Substring(0, 6) + tmpI;
                //    }
                //    else if (range_MeterStart.Length == 12)
                //    {
                //        tmpBH = range_MeterStart.Substring(0, 7) + tmpI;
                //    }
                //    else if (range_MeterStart.Length == 17)
                //    {
                //        tmpBH = range_MeterStart.Substring(0, 12) + tmpI;
                //    }

                //    Application.DoEvents();
                //    List<PackRepeatItem> perRepeat = db01.getRepeatBH(tmpBH, intA);
                //    foreach (PackRepeatItem item in perRepeat)
                //    {
                //        repeatCnt++;
                //        PackRepeatInfo tmpInfo = new PackRepeatInfo();
                //        tmpInfo.No = repeatCnt;
                //        tmpInfo.locatXH = item.locatXH;
                //        tmpInfo.repeatBH = item.repeatBH;
                //        lstRepeatInfo.Add(tmpInfo);
                //    }
                //    lblState.Text = "重复表号数量：" + repeatCnt;
                //}

                Application.DoEvents();
                List<PackRepeatItem> lstAllBH = db01.getAllBHAndLocation(range_MeterStart, range_MeterEnd, range_PackStart, range_PackEnd);
                for (int loopIdx = loopStart; loopIdx <= loopEnd; loopIdx++)
                {
                    tmpI = loopIdx.ToString().PadLeft(5, '0');
                    lblState.Text = "已查询表号数量：" + Convert.ToString(loopIdx - loopStart + 1);

                    //if (range_MeterStart.Length == 11)
                    //{
                    //    tmpBH = range_MeterStart.Substring(0, 6) + tmpI;
                    //}
                    //else if (range_MeterStart.Length == 12)
                    //{
                    //    tmpBH = range_MeterStart.Substring(0, 7) + tmpI;
                    //}
                    //else if (range_MeterStart.Length == 16)
                    //{
                    //    tmpBH = range_MeterStart.Substring(0, 11) + tmpI;
                    //}
                    //else if (range_MeterStart.Length == 17)
                    //{
                    //    tmpBH = range_MeterStart.Substring(0, 12) + tmpI;
                    //}
                    tmpBH = range_MeterStart.Substring(0, range_MeterStart.Length - 5) + tmpI;

                    Application.DoEvents();
                    List<PackRepeatItem> tmpList = lstAllBH.FindAll(
                        delegate(PackRepeatItem repeatItem)
                        {
                            return repeatItem.repeatBH.Equals(tmpBH);
                        });
                    if (tmpList.Count > 1)
                    {
                        repeatCnt++;
                        PackRepeatInfo tmpInfo = new PackRepeatInfo();
                        tmpInfo.No = repeatCnt;
                        tmpInfo.locatXH = tmpList[0].locatXH;
                        tmpInfo.repeatBH = tmpBH;
                        lstRepeatInfo.Add(tmpInfo);
                    }
                }

                if (repeatCnt == 0)
                {
                    MessageUtil.Info("无重复表号");
                    return;
                }
                else
                {
                    frmPackRepeat objRepeatForm = new frmPackRepeat();
                    objRepeatForm.lstRepeatInfo = lstRepeatInfo;
                    objRepeatForm.Text = range_MeterStart + "—" + range_MeterEnd + "范围重复表号浏览窗体";
                    objRepeatForm.ShowDialog();
                }
            }
            else
            {
                GlobalVal.bolNetConnect = false;
                btnNet.Enabled = true;
                MessageUtil.Warn("网络错误，请咨询管理员！");
            }
        }

        /// <summary>
        /// 清除条码
        /// </summary>
        private void ClearLblBarCode()
        {
            lblbarcode1.Text = "";
            lblbarcode2.Text = "";
            lblbarcode3.Text = "";
            lblbarcode4.Text = "";
            lblbarcode5.Text = "";
            lblbarcode6.Text = "";
            strCode = new string[6];
        }

        private void clearTxtBarCode()
        {
            txtBarCode.Text = "";
            txtBarCode.Focus();
        }

        private int getPrintModel(string customerName)
        {
            if ("杭州燃气集团".Equals(customerName))
            {
                return 2;
            }
            else
            {
                return 1;
            }

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void lblbarcode1_Click(object sender, EventArgs e)
        {

        }

        private void txtBarCode_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtBarCode_TextChanged_1(object sender, EventArgs e)
        {

        }
    }
}
